<template>
  <div class="container">
    <table cellspacing="0">
      <tr v-for="arr in cells">
        <template v-for="item in arr">
          <td
            v-if="item.show"
            :rowspan="item.rowspan ? item.rowspan + 1 : 1"
            :colspan="item.colspan ? item.colspan + 1 : 1"
          >
            {{ item.text }}
          </td>
        </template>
      </tr>
    </table>
  </div>
</template>

<script setup>
import { onMounted, ref } from "vue";
import { useRouter } from "vue-router";
import request from "@/libs/request";

const router = useRouter();
const cells = ref([]);

const templateId = router.currentRoute.value.query.templateId;

const ParseJson = (data) => {
  let obj = JSON.parse(data.templateConfig);
  for (let i = 0; i <= obj.range.row; i++) {
    cells.value.push([]);
    for (let j = 0; j <= obj.range.col; j++) {
      cells.value[i].push({
        show: true,
      });
    }
  }

  for (let i = 0; i < obj.cells.length; i++) {
    Object.assign(
      cells.value[obj.cells[i].row][obj.cells[i].col],
      obj.cells[i]
    );
    if (!obj.cells[i].rowspan) obj.cells[i].rowspan = 0;
    if (!obj.cells[i].colspan) obj.cells[i].colspan = 0;
    for (
      let m = obj.cells[i].row;
      m <= obj.cells[i].row + obj.cells[i].rowspan;
      m++
    ) {
      for (
        let n = obj.cells[i].col;
        n <= obj.cells[i].col + obj.cells[i].colspan;
        n++
      ) {
        if (m == obj.cells[i].row && n == obj.cells[i].col) {
          continue;
        }
        cells.value[m][n].show = false;
      }
    }
  }
};

onMounted(() => {
  let loading = ElLoading.service({
    lock: true,
    text: "Getting...",
    background: "rgba(0, 0, 0, 0.7)",
  });
  request({
    url: import.meta.env.VITE_APP_ENV + "/template/" + templateId,
    method: "get",
  })
    .then((res) => {
      if (res.data) {
        ParseJson(res.data);
      } else {
        ElMessage({
          type: "error",
          message: "获取失败！",
        });
      }
      loading.close();
    })
    .catch(() => {
      loading.close();
    });
});
</script>

<style lang="scss" scoped>
.container {
  padding: 20px;

  table {
    color: #7c8db5;
    border: 1px solid #deeaff;

    tr {
      td {
        border: 1px solid #deeaff;
        padding: 0 10px;
        font-size: 18px;
        text-align: center;
        line-height: 38px;
      }
    }
  }
}
</style>
